﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro;
using GTServices.Entities;
using GTServices.Model;

namespace GTServices.WPF.Client.CoRoutines
{
    public class ImportCommand : IResult
    {
        public event EventHandler<ResultCompletionEventArgs> Completed;

        public bool Success { get; set; }
        public List<String> FileNames { get; set; } 

        public ImportCommand(List<String> fileNames)
        {
            FileNames = fileNames;
        }

        public void Execute(ActionExecutionContext context)
        {
            
            foreach (String fileName in FileNames)
            {
                if (System.IO.File.Exists(fileName))
                {
                    using(System.IO.StreamReader sr = new System.IO.StreamReader(System.IO.File.Open(fileName, System.IO.FileMode.Open))){
                        string contents = sr.ReadToEnd();
                        try
                        {
                            Object o = GTApplication.Instance.DataModel.DeserializeXml(contents);

                            if (o is EntityCollection)
                            {
                                EntityCollection ec = o as EntityCollection;
                                foreach (BaseEntity be in ec.Entities)
                                {
                                    GTApplication.Instance.DataModel.CascadeAdd(be, Properties.Settings.Default.UpdateOnAdd);
                                }
                                Success = true;
                            }else if (o is BaseEntity)
                            {
                               
                                //Add (or update)
                                BaseEntity result = GTApplication.Instance.DataModel.CascadeAdd(o as BaseEntity, Properties.Settings.Default.UpdateOnAdd);
                                if (result != null)
                                {
                                    Success = true;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Success = false;
                        }
                    }
                }
                if (Completed != null)
                {
                    Completed(this, new ResultCompletionEventArgs()); 
                }
            }
            
        }
    }
}
